import pandas as pd
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)
# 打印数据集的前5行
print(df.head())

# 使用matplotlib绘制企鹅物种分布的条形图
import matplotlib.pyplot as plt
species_counts = df['Species'].value_counts()
plt.bar(species_counts.index, species_counts.values)
plt.xlabel('Species')
plt.ylabel('Count')
plt.title('Distribution of Penguin Species')
plt.show()

# 使用seaborn绘制每个物种的FlipperLength、CulmenLength和CulmenDepth的箱线图
import seaborn as sns
sns.boxplot(x='Species', y='FlipperLength', data=df)
plt.title('Flipper Length Distribution by Species')
plt.show()

sns.boxplot(x='Species', y='CulmenLength', data=df)
plt.title('Culmen Length Distribution by Species')
plt.show()

sns.boxplot(x='Species', y='CulmenDepth', data=df)
plt.title('Culmen Depth Distribution by Species')
plt.show()

# 显示包含缺失值的行
print(df[df.isnull().any(axis=1)])

# 删除包含缺失值的行
df.dropna(inplace=True)

# 准备训练数据
# 1. 将数据分为特征和标签
features = df[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
labels = df['Species']

# 2. 将数据分为训练集和测试集，其中30%的数据用于测试
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)

# 训练逻辑回归模型
# 1. 创建一个多类逻辑回归模型
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(multi_class='multinomial', solver='lbfgs')

# 2. 训练模型
model.fit(X_train, y_train)

# 评估模型
# 1. 预测测试集的标签
y_pred = model.predict(X_test)

# 2. 计算模型的准确率
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy}")
